<?php

// +----------------------------------------------------------------------
// | 前台会员通行证
// +----------------------------------------------------------------------

namespace Libs\Service;

class Passport extends \Libs\System\Service {

    //存储用户uid的Key
    const userUidKey = 'sh_userid';
    //参数
    protected $options = array();
    //网站配置参数
    protected $config = array();
    //错误信息
    protected $error = null;
    //当前登录会员详细信息
    static protected $userInfo = array();

    /**
     * 连接会员系统
     * @param type $name 服务名
     * @param type $options 参数
     * @return \Libs\Service\class
     */
    public static function connect($name = '', $options = array()) {
        return new Passport($options);
    }

    /**
     * 魔术方法
     * @param type $name
     * @return null
     */
    public function __get($name) {
        //从缓存中获取
        if (isset(self::$userInfo[$name])) {
            return self::$userInfo[$name];
        } else {
            $userInfo = $this->getInfo();
            if (!empty($userInfo)) {
                return $userInfo[$name];
            }
            return NULL;
        }
    }

    /**
     * 获取错误信息
     * @return type
     */
    public function getError() {
        return $this->error;
    }

    /**
     * 获取当前登录用户资料
     * @return array 
     */
    public function getInfo() {
        if (empty(self::$userInfo)) {
            self::$userInfo = $this->getLocalUser($this->getCookieUid());
        }
        return !empty(self::$userInfo) ? self::$userInfo : false;
    }

    /**
     * 获取cookie中记录的用户ID
     * @return type 成功返回用户ID，失败返回false
     */
    public function getCookieUid() {
        $userId = \Libs\Util\Encrypt::authcode(cookie(self::userUidKey), 'DECODE');
        return (int) $userId ? : false;
    }

    /**
     * 获取用户信息
     * @param type $identifier 用户/UID
     * @param type $password 明文密码，填写表示验证密码
     * @return array|boolean
     */
    public function getLocalUser($identifier, $password = null) {
        $map = array();
        if (empty($identifier)) {
            $this->error = '参数为空！';
            return false;
        }
        if (is_int($identifier) && strlen($identifier)<11) {
            $map['userid'] = $identifier;
        } else {
            $map['uname'] = $identifier;
        }
        $UserMode = D('User/User');
        $user = $UserMode->where($map)->find();
        if (empty($user)) {
            $this->error = '该用户不存在！';
            return false;
        }
        //是否需要进行密码验证
        if (!empty($password)) {
            $authkey = $user["authkey"];
            //对明文密码进行加密
            $password = $UserMode->encryption($identifier, $password, $authkey);
            if ($password != $user['upassword']) {
                $this->error = '用户密码错误！';
                //密码错误
                return false;
            }
        }
        return $user;
    }


    /**
     * 会员登录
     * @param type $identifier 用户/UID
     * @param type $password 明文密码，填写表示验证密码
     * @param type $is_remember_me cookie有效期
     * @return boolean
     */
    public function loginLocal($identifier, $password = null, $is_remember_me = 604800) {
        $map = array();
        if (is_int($identifier) && strlen($identifier)<11) {
            $map['userid'] = $identifier;
            $identifier = intval($identifier);
        } else {
            $map['uname'] = $identifier;
        }
        $userinfo = $this->getLocalUser($identifier);
        if (empty($userinfo)) {
            return false;
        }
        //是否需要进行密码验证
        if (!empty($password)) {
            $authkey = $userinfo['authkey'];
            //对明文密码进行加密
            $password = D("User/User")->encryption($identifier, $password, $authkey);
            if ($password != $userinfo['upassword']) {
                $this->error = '密码错误！';
                return false;
            }
        }

        //注册用户登陆状态
        if ($this->registerLogin($userinfo, $is_remember_me)) {
            //修改登陆时间，和登陆IP
            D("User/User")->where($map)->save(array(
                "login_time" => time(),
                "lastip" => get_client_ip(),
                "logtimes" => $userinfo['logtimes'] + 1,
            ));
            //登陆成功
            return $userinfo['userid'];
        }else{
            $this->error = '用户注册状态状态失败！';
            return false;
        }

    }
    /**
     * 获取用户头像 
     * @param type $uid 用户ID
     * @param int $format 头像规格，默认参数90，支持 180,90,45,30
     * @param type $dbs 该参数为true时，表示使用查询数据库的方式，取得完整的头像地址。默认false
     * @return type 返回头像地址
     */
    public function getUserAvatar($uid, $format = 90, $dbs = false) {
        $config = cache('Config');
        return "{$config['siteurl']}static/home/images/default_touxiang.jpg";
    }


    /**
     * 用户动态
     * @param $uid
     * @param $credits
     * @param $content
     * @param $type 是增加还是减少积分
     * @return bool
     */
    public function userDynamic($uid, $credits, $content, $type, $action,$infoid='') {
        $map = array();
        $map['userid'] = $uid;
        if (empty($map)) {
            $this->error = '该用户不存在！';
            return false;
        }
        $member = M('User');
        $info = $member->where($map)->find();
        if (empty($info)) {
            $this->error = '该用户不存在！';
            return false;
        }
        if($type==1){
            $upoint = $info['upoint'] + $credits;
        }else{
            $upoint = $info['upoint'] - $credits;
            if($upoint <= 0){
                $upoint = 0 ;
            }
        }
        $data['content']=$content;
        $data['create_time']=time();
        $data['credits']=$credits;
        $data['userid']=$uid;
        $data['action']=$action;
        $data['infoid']=$infoid;
        $data['status']=true;
        //更新
        if ($member->where($map)->save(array("upoint" => (int) $upoint))) {
             M('UserDynamic')->add($data);
             
            return true;
        }
        $this->error = '积分操作失败！';
        return false;
    }


    /**
     * 检验用户是否已经登陆
     */
    public function isLogged() {
        //获取cookie中的用户id
        $uid = $this->getCookieUid();
        if (empty($uid) || $uid < 1) {
            return false;
        }
        return $uid;
    }

    /**
     * 注册用户的登陆状态 (即: 注册cookie + 注册session + 记录登陆信息)
     * @param array $user 用户相关信息 uid , username
     * @param type $is_remeber_me 有效期
     * @return type 成功返回布尔值
     */
    public function registerLogin(array $user, $is_remeber_me = 604800) {
        $key = \Libs\Util\Encrypt::authcode((int) $user['userid'], '');
        cookie(self::userUidKey, $key, (int) $is_remeber_me);
        return true;
    }

    /**
     * 注销登陆
     * @return boolean
     */
    public function logoutLocal() {
        // 注销cookie
        cookie(self::userUidKey, null);
        return true;
    }



    /**
     * 记录登陆信息
     * @param type $uid 用户ID
     */
    public function recordLogin($uid) {
        return true;
    }

    /**
     * 注册会员
     * @param type $username 用户名
     * @param type $password 明文密码
     * @param type $email 邮箱
     * @return boolean
     */
    public function userRegister($username, $password) {
        //检查用户名
        $ckname = $this->userCheckUsername($username);
        if ($ckname !== true) {
            return false;
        }

        $Member = D("User/User");
        $encrypt = genRandomString(6);
        $password = $Member->encryption(0, $password, $encrypt);
        $data = array(
            "uname" => $username,
            "upassword" => $password,
            "authkey" => $encrypt,
        );
        $userid = $Member->add($data);
        if ($userid) {
            return $userid;
        }else{
            $this->error = $Member->getError()? : '注册失败！';
            return false;
        }

    }

    /**
     * 检查用户名
     * @param type $username 用户名
     * @return boolean|int
     */
    public function userCheckUsername($username) {
        $guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8';
        if (!preg_match("/\s+|^c:\\con\\con|[%,\*\"\s\<\>\&]|$guestexp/is", $username)) {
            $find = M("User")->where(array("uname" => $username))->count();
            if ($find) {
                $this->error = '该用户名已经存在！';
                return false;
            }
            return true;
        }
        $this->error = '用户名不合法！';
        return false;
    }

    /**
     * 检查 Email 地址
     * @param type $email 邮箱地址
     * @return boolean
     */
    public function userCheckeMail($email) {
        if (strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email)) {
            $find = M('User')->where(array("uemail" => $email))->count();
            if ($find) {
                $this->error = '该 Email 已经被注册！';
                return false;
            }
            return true;
        }
        $this->error = 'Email 格式有误！';
        return false;
    }
    /**
     * 更新用户基本资料
     * @param type $username 用户名
     * @param type $oldpw 旧密码
     * @param type $newpw 新密码，如不修改为空
     * @param type $email Email，如不修改为空
     * @param type $ignoreoldpw 是否忽略旧密码
     * @param type $data 其他信息
     * @return boolean
     */
    public function userEdit($username, $oldpw, $newpw = '', $email = '', $ignoreoldpw = 0, $data = array()) {
        return false;
    }

    /**
     * 删除用户
     * @param type $uid 用户UID
     * @return boolean
     */
    public function userDelete($uid) {
        return true;
    }

    /**
     * 删除用户头像
     * @param type $uid 用户名UID
     * @return boolean
     */
    public function userDeleteAvatar($uid) {
        return false;
    }




    /**
     * 修改头像
     * @param type $uid 用户 ID
     * @param type $type 头像类型
     *                                       real:真实头像
     *                                       virtual:(默认值) 虚拟头像
     * @param type $returnhtml 是否返回 HTML 代码
     *                                                     1:(默认值) 是，返回设置头像的 HTML 代码
     *                                                     0:否，返回设置头像的 Flash 调用数组
     * @return string:返回设置头像的 HTML 代码
     *                array:返回设置头像的 Flash 调用数组
     */
    public function userAvatarEdit($uid, $type = 'virtual', $returnhtml = 1) {
        return false;
    }

    /**
     * 获取头像存储路径
     * @param type $uid 会员UID
     * @return type
     */
    public function getAvatarPath($uid) {
        $uid = abs(intval($uid)); //UID取整数绝对值
        $uid = sprintf("%09d", $uid); //前边加0补齐9位，例如UID为31的用户变成 000000031
        $dir1 = substr($uid, 0, 3);  //取左边3位，即 000
        $dir2 = substr($uid, 3, 2);  //取4-5位，即00
        $dir3 = substr($uid, 5, 2);  //取6-7位，即00
        return 'user/' . $dir1 . '/' . $dir2 . '/' . $dir3 . '/';
    }

}

